
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

public class SocketServer {
    public static void main(String[] args)  throws  IOException{
        // 1. 创建ServerSocket，指定监听的端口号
        ServerSocket serverSocket = new ServerSocket(8080);
        System.out.println("服务端已启动 8080");

        // 2. 循环等待客户端连接
        while (true) {
            // 3. accept()方法阻塞，直到有客户端连接
            Socket clientSocket = serverSocket.accept();

            System.out.println("Accepted connection from: " + clientSocket.getInetAddress());

            // 4. 处理客户端连接（这里我们创建新的线程处理，以免阻塞其他客户端）
            new Thread(new ClientHandler(clientSocket)).start();
        }

    }

    // 5. 定义处理客户端的线程类
    private static class ClientHandler implements Runnable {
        private Socket client;

        public ClientHandler(Socket client) {
            this.client = client;
        }

        @Override
        public void run() {
            try (BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));
                 PrintWriter out = new PrintWriter(client.getOutputStream(), true)) {

                String inputLine;
                while ((inputLine = in.readLine()) != null) {
                    System.out.println("Received message: " + inputLine);
                    // 可以在这里处理客户端发送的数据，例如回复消息
                    out.println("Server received your message: " + inputLine);
                }

            } catch (IOException e) {
                System.err.println("Error handling client: " + e.getMessage());
            } finally {
                try {
                    if (client != null)
                        client.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }
    }
}
